package uk.co.agileworks.bidpirate.service;

import javax.annotation.Resource;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

import uk.co.agileworks.bidpirate.model.User;

@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.NO)
public final class EbaySessionImpl implements EbaySession {

	private static final Logger LOGGER = LoggerFactory.getLogger(EbayFacadeImpl.class);

	private static final boolean ENABLE_JAVASCRIPT = false;

	private WebDriver driver;
	@Resource
	private String defaultUrl;
	@Resource
	private String signInUrl;

	public EbaySessionImpl() {
		driver = new HtmlUnitDriver(ENABLE_JAVASCRIPT);
	}

	@Override
	public boolean isSignedIn() {
		driver.get(defaultUrl);
		WebElement strong = driver.findElement(By.xpath("//td[@class='ttext']/strong"));
		LOGGER.debug(strong.getText());
		return !strong.getText().equals("Welcome!");
	}

	@Override
	public boolean signIn(User user) {
		driver.get(signInUrl);
		WebElement uid = driver.findElement(By.xpath("//input[@name='uid']"));
		WebElement upw = driver.findElement(By.xpath("//input[@name='upw']"));
		WebElement btnSubmit = driver.findElement(By.xpath("//input[@name='btnSubmit']"));
		uid.sendKeys(user.getUsername());
		upw.sendKeys(user.getPassword());
		btnSubmit.click();
		LOGGER.debug(driver.getTitle());
		return !driver.getTitle().equals("eBay Mobile Sign in");
	}

	@Override
	public void signOut() {
		driver.get(signInUrl + "?so=Logout");
	}

}
